//
// Description: 290. 单词规律
// Created by Loading on 2025/4/13.
//

#include <bits/stdc++.h>

using namespace std;

bool wordPattern(string pattern, string s) {
    unordered_map<char, string> p2s;
    unordered_map<string, char> s2p;

    int n = s.size();
    int index = 0;
    for (auto & c : pattern) {
        if (index >= n) { // pattern长度大于s中的单词数
            return false;
        }
        int j = index;
        while (j < n && s[j] != ' ') {
            ++j;
        }
        string tmp = s.substr(index, j - index);
        if (p2s.count(c) && p2s[c] != tmp) {
            return false;
        }
        if (s2p.count(tmp) && s2p[tmp] != c) {
            return false;
        }
        p2s[c] = tmp;
        s2p[tmp] = c;
        index = j + 1;
    }

    // s中的单词数大于pattern长度
    return index >= n;
}

int main() {
    string pattern = "abba";
    string s = "dog cat cat fish";

    auto res = wordPattern(pattern, s);

    cout << res << endl;

    return 0;
}
